from django.shortcuts import render
import logging

import random
from django_redis import get_redis_connection
from django.views import View
from django.http import HttpResponse
from django.http import JsonResponse
from celery_tasks.sms.tasks import ccp_send_sms_code
from meiduo_mall.libs.yuntongxun.ccp_sms import CCP
from meiduo_mall.libs.captcha.captcha import captcha
logger = logging.getLogger('django')

# Create your views here.


class ImageCodeView(View):
    def get(self, request, uuid):
        # 生成图片验证码
        text, image = captcha.generate_captcha()
        # 连接redis 数据库
        redis_conn = get_redis_connection('verify_code')
        # 向redis保存图片验证码数据
        redis_conn.setex('img_%s' % uuid, 300, text)
        # 返回图片验证码
        return HttpResponse(image, content_type='image/jpg')


class SMSCodeView(View):
    def get(self, request, mobile):
        # 获取参数
        image_code = request.GET.get('image_code')
        uuid = request.GET.get('image_code_id')

        # 判断 参数是否为空
        if not all([image_code, uuid]):
            return JsonResponse({'code': 400, 'errmsg': '缺少必须传递参数'})

        # redis建立连接
        redis_conn = get_redis_connection('verify_code')

        # 获取图片验证数据,手机号发送标志位
        image_code_value = redis_conn.get('img_%s' % uuid)
        send_flag_mobile = redis_conn.get(f'send_flag_{mobile}')

        # 判断是否频繁发送验证码
        if send_flag_mobile:
            return JsonResponse({'code': 400, 'errmsg': '重复获取验证码'})

        # 判断图形验证码是否过期
        if not image_code_value:
            return JsonResponse({'code': 400, 'errmsg': '图形验证码失效'})

        # 尝试在redis数据库删除图形验证码
        try:
            redis_conn.delete('img_%s' % uuid)
        except Exception as e:
            logger.error(e)

        # 将redis保存的二进制数据转换编码
        code = image_code_value.decode()

        # 对比验证码数据是否一致
        if code.lower() != image_code.lower():
            return JsonResponse({'code': 400, 'errmsg': '输入图形验证码错误'})

        # 随即生成短信验证码
        sms_code = '%06d' % random.randint(0, 999999)
        logger.info(sms_code)

        # 创建redis管道
        rs_pl = redis_conn.pipeline()

        # 将redis请求加入到队列
        rs_pl.setex('sms_%s' % mobile, 300, sms_code)
        rs_pl.setex(f'send_flag_{mobile}', 60, '1')

        # 执行队列请求
        rs_pl.execute()

        # 生产环境
        ccp_send_sms_code.delay(mobile, sms_code)

        return JsonResponse({'code': 0, 'errmsg': '发送短信成功'})
